var TRACKING = {
	contextPath : '/tracker/',
	eventStack : new Array(),

	createEvent : function(type, payload, reference) {
		var event = new Object();
		if (!type || type == null || type == "")
			throw new NullPointerException('type');
		event.type = type;
		event.payload = payload;
		event.reference = reference;

		event.time = new Date();
		event.HTMLSender = this.getHTMLSender();
		event.session = this.getSession();

		TRACKING.eventStack[this.eventStack.length] = event;
		return event;
	},

	getHTMLSender : function() {
		var sender = new Object();
		sender.secure = location.protocol == 'https:';
		sender.hostName = location.host;
		sender.uri = location.pathname;
		sender.parameters = location.search;
		return sender;
	},

	getSession : function() {
		var session = getCookie('tr_cookie');
		if (session == undefined) {
			session = TRACKING.generateSession();
			setCookie('tr_cookie', session, 14);
		}
		return session;
	},

	generateSession : function() {
		var req = new XMLHttpRequest();
		var r;
		req.open('GET', this.contextPath + 'CreateSession', false);
		req.send();
		r = req.responseText;
		return r;
	},
	convertEventToXML : function(event) {
		xmlBody = '<Event>\n';
		xmlBody += ' <Type><EventName>' + event.type + '</EventName></Type>\n';
		xmlBody += ' <HTMLSender>\n';
		xmlBody += ' <Secure>' + event.HTMLSender.secure + '</Secure>\n';
		xmlBody += ' <HostName>' + event.HTMLSender.hostName + '</HostName>\n';
		xmlBody += ' <URL>' + event.HTMLSender.uri + '</URL>\n';
		xmlBody += ' <Parameters>' + escape(event.HTMLSender.parameters) + '</Parameters>\n';
		xmlBody += ' </HTMLSender>\n';
		xmlBody += ' <Session><TokenID>' + event.session + '</TokenID></Session>\n';
		xmlBody += ' <Payload>' + escape(event.payload) + '</Payload>\n';
		// 2006-08-29T01:18:15.001Z
		xmlBody += ' <Time>' + event.time.getFullYear() + '-';
		xmlBody += (((event.time.getMonth() + 1) + '').length == 1 ? '0' + (event.time.getMonth() + 1) : (event.time.getMonth() + 1)) + '-';
		xmlBody += ((event.time.getDate() + '').length == 1 ? '0' + event.time.getDate() : event.time.getDate()) + 'T';
		xmlBody += ((event.time.getHours() + '').length == 1 ? '0' + event.time.getDate() : event.time.getDate()) + ':';
		xmlBody += event.time.getMinutes() + ':';
		xmlBody += event.time.getSeconds() + '.';
		xmlBody += event.time.getMilliseconds() + '</Time>\n';
		// xmlBody += '<Reference>' + event.reference + '</Reference>';
		xmlBody += '</Event>\n';
		return xmlBody;
	},
	commit : function() {
		if (this.retroUnload != undefined)
			this.retroUnload();

		var xmlBody = '<?xml version="1.0"?>\n';
		xmlBody += '<Events xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://' + location.hostname + ':' + location.port
				+ TRACKING.contextPath + 'EventSchemaV3.xsd">';
		for (i = 0; i < TRACKING.eventStack.length; i++) {
			xmlBody += TRACKING.convertEventToXML(TRACKING.eventStack[i]);
		}
		TRACKING.eventStack = new Array();
		xmlBody += '</Events>';
		var req = new XMLHttpRequest();
		req.open('POST', TRACKING.contextPath + 'submit', true);
		req.setRequestHeader("Content-type", "text/xml");
		req.send(xmlBody);
	}

};

// Source http://www.w3schools.com/js/js_cookies.asp
// TODO: replace this.
function getCookie(c_name) {
	var i, x, y, ARRcookies = document.cookie.split(";");
	for (i = 0; i < ARRcookies.length; i++) {
		x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
		y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
		x = x.replace(/^\s+|\s+$/g, "");
		if (x == c_name)
			return unescape(y);
	}
};

function setCookie(c_name, value, exdays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
	document.cookie = c_name + "=" + c_value;
};
// End borrowed code.

// TODO: add routine updates

TRACKING.retroUnload = window.onbeforeunload;
window.onbeforeunload = TRACKING.commit;